package com.example.aspect;
import com.example.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.List;

@Component
@Aspect
@Slf4j
public class InitAspect {
    @Around("@annotation(com.example.log.InitLog)")
    public Result init(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("新增操作时aop_init增强执行~");
        Object[] args = joinPoint.getArgs();
        Object obj = args[0];
        if (obj instanceof List) {
            List<?> list = (List<?>) obj;
            for (Object item : list) {
                initParameter(item);
            }
        } else {
            initParameter(obj);
        }
        //执行原方法
        Object proceed = joinPoint.proceed();
        return (Result) proceed;
    }
    private void initParameter (Object item) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        Class<?> clazz = item.getClass();
        Method setCreateTime = clazz.getDeclaredMethod("setCreateTime",LocalDateTime.class);
        Method setUpdateTime = clazz.getDeclaredMethod("setUpdateTime",LocalDateTime.class);
        setCreateTime.setAccessible(true);
        setCreateTime.invoke(item, LocalDateTime.now());
        setUpdateTime.setAccessible(true);
        setUpdateTime.invoke(item, LocalDateTime.now());
    }
}
